# -*-coding: utf-8 -*-
"""
    @Theme   : 博客前台
    @Time    : 2024/4/10 12:50
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
from flask import Blueprint, render_template, request, current_app, redirect, url_for, flash, abort, make_response
from flask_login import current_user

from suzyblog.models import Post, Category, Comment
from suzyblog.forms import CommentForm, AdminCommentForm
from suzyblog.extensions import db
from suzyblog.email import mail_new_comment, mail_new_reply
from suzyblog.utils import redirect_back

blog_bp = Blueprint('blog', __name__)


@blog_bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    per_page = current_app.config['BLOG_POST_PER_PAGE']
    pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page=page, per_page=per_page)
    return render_template('blog/index.html', pagination=pagination, posts=pagination.items)


@blog_bp.route('/category/<int:category_id>')
def show_category(category_id):
    category = Category.query.get_or_404(category_id)
    page = request.args.get('page', 1, type=int)
    per_page = current_app.config['BLOG_POST_PER_PAGE']
    pagination = Post.query.with_parent(category).order_by(Post.timestamp.desc()).paginate(page=page, per_page=per_page)
    return render_template('blog/category.html', category=category, pagination=pagination, posts=pagination.items)


@blog_bp.route('/post/<int:post_id>', methods=['GET', 'POST'])
def show_post(post_id):
    post = Post.query.get_or_404(post_id)

    page = request.args.get('page', 1, type=int)
    per_page = current_app.config['BLOG_COMMENT_PER_PAGE']
    pagination = Comment.query.with_parent(post).filter_by(reviewed=True)\
        .order_by(Comment.timestamp.desc()).paginate(page=page, per_page=per_page)
    comments = pagination.items

    if current_user.is_authenticated:
        form = AdminCommentForm()
        form.author.data = current_user.name
        form.email.data = current_app.config['BLOG_EMAIL']
        form.site.data = url_for('blog.index')
        from_admin = True
        reviewed = True
    else:
        form = CommentForm()
        from_admin = False
        reviewed = False

    if form.validate_on_submit():
        author = form.author.data
        email = form.email.data
        site = form.site.data
        body = form.body.data
        comment = Comment(author=author, email=email, site=site, body=body,
                          from_admin=from_admin, reviewed=reviewed, post=post)
        replied_id = request.args.get('reply')
        if replied_id:
            reply = Comment.query.get_or_404(replied_id)
            comment.replied = reply
            mail_new_reply(reply)
        db.session.add(comment)
        db.session.commit()

        if current_user.is_authenticated:
            flash('Comment Published Success!', 'success')
        else:
            flash('Your Comment will be Published after Reviewed!', 'info')
            mail_new_comment(post)
        return redirect(url_for('blog.show_post', post_id=post.id))
    return render_template('blog/post.html', post=post, pagination=pagination, comments=comments, form=form)


@blog_bp.route('/about')
def about():
    return render_template('blog/about.html')


@blog_bp.route('/reply/comment/<int:comment_id>')
def reply_comment(comment_id):
    comment = Comment.query.get_or_404(comment_id)
    return redirect(url_for('blog.show_post', post_id=comment.post_id, reply=comment_id,
                            author=comment.author) + '#comment-form')


@blog_bp.route('/change-theme/<theme_name>')
def change_theme(theme_name):
    if theme_name not in current_app.config['BLOG_THEMES']:
        abort(404)
    response = make_response(redirect_back())
    response.set_cookie('theme', theme_name, max_age=365*30*24*60*60)
    return response
